package com.project.server.controller;

import com.project.server.common.api.Result;
import com.project.server.dto.LoginDTO;
import com.project.server.dto.LoginVO;
import com.project.server.dto.RegisterDTO;
import com.project.server.entity.SysUser;
import com.project.server.service.SysUserService;
import com.project.server.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired(required = false)
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO loginDTO) {
        LoginVO user = sysUserService.login(loginDTO);
        String token = JwtUtil.generateToken(user.getUsername(), user.getUserId());

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", user);

        return Result.success(result);
    }

    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        SysUser user = sysUserService.getById(userId);

        if (user == null) {
            return Result.error(401, "用户不存在");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("username", user.getUsername());
        data.put("realName", user.getRealName());
        data.put("avatar", user.getAvatar());
        data.put("roleId", user.getRoleId());
        data.put("userId", user.getId());

        return Result.success(data);
    }

    @PostMapping("/logout")
    public Result<Void> logout() {
        return Result.success();
    }

    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> register(@Valid @RequestBody RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (sysUserService.getByUsername(registerDTO.getUsername()) != null) {
            return Result.error("用户名已存在");
        }

        // 创建用户
        SysUser user = new SysUser();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setRealName(registerDTO.getRealName());
        user.setPhone(registerDTO.getPhone());
        user.setRoleId(registerDTO.getRoleId());
        user.setStatus(1);

        sysUserService.save(user);

        return Result.success();
    }
}
